<template>
  <div id="app">
    <el-card>
      <template #header>
        <div class="flex justify-between items-center">
          <span>MinIO 文件上传</span>
        </div>
      </template>
      <el-form ref="formRef" :model="formData" label-width="100px">
        <el-form-item label="选择文件">
          <el-upload ref="uploadRef" action="https://localhost:7212/api/FileUpload/UploadFile" :headers="headers"
            :on-success="handleSuccess" :on-error="handleError" :show-file-list="false" :http-request="customRequest">
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">上传文件</el-button>
        </el-form-item>
      </el-form>
      <el-alert v-if="message" :message="message" :type="messageType" :closable="false" style="margin-top: 20px" />
    </el-card>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="key" label="文件名称" width="200" />
      <el-table-column prop="lastModified" label="创建时间" width="200">
        <template #default="scope">
          {{ new Date(scope.row.lastModified).toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column prop="size" label="文件大小" min-width="200" />
      <el-table-column fixed="right" label="操作" min-width="200">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="openDeleteDialog(scope.row.key)">
            删除文件
          </el-button>
          <el-button link type="primary" size="small" @click="download(scope.row.key)">下载文件</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="isDeleteDialogVisible" title="删除确认" @close="closeDeleteDialog">
      <p>确定要删除该文件吗？</p>
      <template #footer>
        <el-button @click="closeDeleteDialog">取消</el-button>
        <el-button type="primary" @click="confirmDelete">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="isDownloadDialogVisible" title="文件下载">
      <template #content>
        <el-progress :percentage="downloadProgress" :status="downloadStatus"></el-progress>
      </template>
      <template #footer>
        <el-button @click="closeDownloadDialog">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import axios from 'axios';
import { ElDialog } from 'element-plus';
import { read, write } from '@/axios/axiosHelper';

const formRef = ref(null);
const uploadRef = ref(null);
const formData = ref({});
const message = ref('');
const messageType = ref('');
const tableData = ref([{
  key: "",
  lastModified: "",
  eTag: "",
  size: 0,
  isDir: false,
  versionId: null,
  contentType: null,
  expires: null,
  userMetadata: null,
  isLatest: false,
  lastModifiedDateTime: "",
}]);
const isDeleteDialogVisible = ref(false);
const currentDeleteKey = ref('');
const isDownloadDialogVisible = ref(false);
const downloadProgress = ref(0);
const downloadStatus = ref('');

onMounted(() => {
  listObjects();
});

const download = async (key) => {
  isDownloadDialogVisible.value = true;
  downloadProgress.value = 0;
  downloadStatus.value = 'active';
  try {
    const response = await axios.get(`/api/FileUpload/DownloadFile?objectName=${key}`, {
      responseType: 'blob',
      onDownloadProgress: (progressEvent) => {
        const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        downloadProgress.value = percentCompleted;
      }
    });
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', key);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    downloadStatus.value = 'success';
  } catch (error) {
    console.error('文件下载失败:', error);
    message.value = '文件下载失败: ' + (error.response?.data?.error || error.message);
    messageType.value = 'error';
    downloadStatus.value = 'exception';
  }
};

const listObjects = async () => {
  axios.get("https://localhost:7212/api/FileUpload/ListObjectsInOneBucket")
    .then((res) => {
      tableData.value = res.data;
      console.log("查询成功", res.data);
    })
    .catch((err) => {
      console.log(err);
    });
};

const headers = {
  'Content-Type': 'multipart/form-data'
};

const customRequest = async (options) => {
  const formData = new FormData();
  formData.append('file', options.file);
  const response = await axios.post(options.action, formData, {
    headers: headers
  });
  options.onSuccess(response.data);
  if (response.data != null) {
    alert("添加成功");
    return;
  } else {
    alert("添加失败");
    return;
  }
};

const handleError = (error) => {
  message.value = '上传失败: ' + (error.response?.data?.error || error.message);
  messageType.value = 'error';
};

const submitForm = () => {
  uploadRef.value.submit();
};

const openDeleteDialog = (key) => {
  currentDeleteKey.value = key;
  isDeleteDialogVisible.value = true;
};

const closeDeleteDialog = () => {
  isDeleteDialogVisible.value = false;
  currentDeleteKey.value = '';
};

const confirmDelete = () => {
  axios.delete("https://localhost:7212/api/FileUpload/DeleteObjectInOneBucket", {
    params: {
      objectName: currentDeleteKey.value
    }
  })
    .then((res) => {
      console.log("删除成功", res.data);
      message.value = '文件删除成功';
      messageType.value = 'success';
      listObjects();
      closeDeleteDialog();
    })
    .catch((err) => {
      console.log(err);
      message.value = '文件删除失败: ' + (err.response?.data?.error || err.message);
      messageType.value = 'error';
      closeDeleteDialog();
    });
};

const closeDownloadDialog = () => {
  isDownloadDialogVisible.value = false;
  downloadProgress.value = 0;
  downloadStatus.value = '';
};
</script>

<style scoped>
#app {
  padding: 20px;
}
</style>    